package models.misc
{
	import flash.events.EventDispatcher;
	import flash.net.SharedObject;

	public class SettingsManager extends EventDispatcher
	{
		private static var settings:Array;
		private static var so:SharedObject;
		
		public static function getSetting(key:String):Object{
			if( settings == null ){ getPrefFromSharedObject(); };	
			
			var i:int = 0;
			var max:int = settings.length;			
			for( i=0; i<max; i++ ){
				if( settings[i].key == key ){
					return settings[i].value;
				}
			}
			return null;
		}
		
		public static function clearSetting(key:String):void{
			if( settings == null ){ getPrefFromSharedObject(); };	
		
			var i:int = 0;
			var max:int = settings.length;
			
			//if settings exist change the value
			for( i=0; i<max; i++ ){
				if( settings[i].key == key ){
					settings[i].value = null;
					return;
				}
			}
			saveSettingsToSharedObject();
		}
		
		public static function saveSetting(key:String, value:Object):void{
			if( settings == null ){ getPrefFromSharedObject(); };	
		
			var i:int = 0;
			var max:int = settings.length;
			
			//if settings exist change the value
			for( i=0; i<max; i++ ){
				if( settings[i].key == key ){
					settings[i].value = value;
					return;
				}
			}
			
			//otherwise add new value
			settings.push( {key:key, value:value} );
			saveSettingsToSharedObject();
		}
		
		private static function saveSettingsToSharedObject():void{
			if( settings == null ) { getPrefFromSharedObject() }
			so.data.settings = settings;
			so.flush();
		}
			
		private static function getPrefFromSharedObject():void{
			so = SharedObject.getLocal('preferences'); 
			if( so.data.settings == null){
				so.data.settings = [];
			}
			settings = so.data.settings;
		}
	}
}